package com.gnerv.cms.job;

import com.gnerv.cms.common.CommonString;
import com.gnerv.cms.dto.TaskDTO;
import com.gnerv.cms.dto.TaskSaveDTO;
import com.gnerv.cms.service.ITaskService;
import com.google.gson.Gson;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.time.LocalDateTime;

public class DefaultJob extends QuartzJobBean {

    @Resource
    Scheduler scheduler;

    @Resource
    ITaskService taskService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        JobDataMap mergedJobDataMap = jobExecutionContext.getMergedJobDataMap();
        String taskJson = (String) mergedJobDataMap.get(CommonString.TASK_DATA_MAP_KEY);
        TaskSaveDTO taskSaveDTO = new Gson().fromJson(taskJson, TaskSaveDTO.class);
        TaskDTO taskDTO = taskService.selectTask(taskSaveDTO.getUkId());
        Integer total = taskDTO.getTotal();
        if(total == -1){
            total = Integer.MAX_VALUE;
        }
        if(total > taskDTO.getCount()){
            System.out.println(taskSaveDTO + " 系统任务开始：" + LocalDateTime.now());
            taskService.updateTaskCount(taskDTO.getUkId());
        }else {
            taskService.stopTask(taskDTO.getUkId());
        }
    }
}
